//
//  TMRcImManger.m
//  GoldChampion
//
//  Created by Mac on 2018/5/17.
//  Copyright © 2018年 stoneobs@icloud.com. All rights reserved.
//

#import "TMRcImManger.h"
#import<CommonCrypto/CommonDigest.h>
@interface TMRcImManger()<RCIMUserInfoDataSource>
@property(nonatomic, strong) NSString                     *rcAppKey;/**< rcAppKey */
@property(nonatomic, strong) NSString                     *appSecret;/**< appSecret */
@end
@implementation TMRcImManger
+ (TMRcImManger *)manger{
    static TMRcImManger * manger = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manger = [TMRcImManger new];
    });
    return manger;
}

- (void)registerRcAppKey:(NSString *)rcAppKey appSecret:(NSString *)appSecret{
    [[RCIM sharedRCIM] initWithAppKey:rcAppKey];
    self.rcAppKey = rcAppKey;
    self.appSecret = appSecret;
    [RCIM sharedRCIM].userInfoDataSource = self;;
}
- (void)logout{
    [[RCIM sharedRCIM] logout];
}
- (void)loginWithUserId:(NSString *)userId nickName:(NSString *)nickName iconUrl:(NSString *)iconUrl handle:(void (^)(NSString *))handle{
    if (![TMRcImManger manger].appSecret.length) {
        DDLogError(@"请先 registerRcAppKey");
        return;
    }
    nickName = nickName.length?nickName:@"";
    iconUrl = iconUrl.length?iconUrl:@"";
    
    RCUserInfo * info = [RCUserInfo new];
    info.userId = userId;
    info.name = nickName;
    info.portraitUri = iconUrl;

    
    [self.class fecthRCTokenWithUserID:userId nickName:nickName iconUrl:iconUrl handle:^(NSString *token) {
        //使用融云的IMKit登录方式
        if (token.length) {
            [[RCIM sharedRCIM] connectWithToken:token success:^(NSString *userId) {
                if (handle) {
                    handle(@"");
                }
                DDLogInfo(@"IMKit登陆成功。当前登录的用户ID：%@", userId);
                [RCIM sharedRCIM].currentUserInfo = info;
                [RCIM sharedRCIM].enableMessageAttachUserInfo = YES;
                
            } error:^(RCConnectErrorCode status) {
                DDLogInfo(@"IMKit登陆的错误码为:%ld", (long)status);
                if (handle) {
                    handle(@"失败");
                }
            } tokenIncorrect:^{
                DDLogInfo(@"IMKit token错误");
                if (handle) {
                    handle(@"token错误");
                }
            }];
        }else{
            DDLogInfo(@"融云token 登录失败");
            if (handle) {
                handle(@"获取token失败");
            }
        }
        
    }];
}
+ (void)fecthRCTokenWithUserID:(NSString *)userID nickName:(NSString *)nickName iconUrl:(NSString *)iconUrl handle:(void (^)(NSString *))handle{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10;
    NSString * url = @"http://api.cn.ronghub.com/user/getToken.json";
    nickName = nickName.length?nickName:@"";
    iconUrl = iconUrl.length?iconUrl:@"";
    NSDictionary * dic = @{@"userId":userID,@"name":nickName,@"portraitUri":iconUrl};
    
    NSString * nonce = [self.class randromString];
    NSString * time = [self.class timeString];
    NSString * signature = [self.class sha1WithAppSecret:[TMRcImManger manger].appSecret nonce:nonce time:time];
    
    [manager.requestSerializer setValue:[TMRcImManger manger].rcAppKey forHTTPHeaderField:@"App-Key"];
    [manager.requestSerializer setValue:nonce forHTTPHeaderField:@"Nonce"];
    [manager.requestSerializer setValue:time forHTTPHeaderField:@"Timestamp"];
    [manager.requestSerializer setValue:signature forHTTPHeaderField:@"Signature"];
    
    
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    [manager POST:url parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary * resDic = responseObject;
        if (handle) {
            NSString * token = resDic[@"token"];
            handle(token);
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (handle) {
            NSString * token = @"";
            handle(token);
        }
    }];
    
}
- (void)updateSendUserInfoWithName:(NSString *)nickname iconUrl:(NSString *)iconUrl{
    RCUserInfo * info = [RCIM sharedRCIM].currentUserInfo;
    info.name = nickname;
    info.portraitUri = iconUrl;
    [RCIM sharedRCIM].currentUserInfo = info;
    [RCIM sharedRCIM].enableMessageAttachUserInfo = YES;
}
#pragma mark --RCIMUserInfoDataSource
- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *userInfo))completion{
    // 更新数据
//    [TMUtils fecthUserModelWithUserId:userId handle:^(GCUserModel *user) {
//        RCUserInfo *userInfo =  [RCUserInfo new];
//        userInfo.userId = userId;
//        userInfo.name = user.nickname;
//        if (!userInfo.name.length) {
//            userInfo.name = @"金冠用户";
//        }
//        userInfo.portraitUri = user.headUrl;
//        completion(userInfo);
//    }];
}
#pragma mark --Private Method
+ (NSString*)randromString{
    NSInteger index = arc4random()%1000;
    return @(index).description;
}
+ (NSString*)timeString{
    NSInteger  num = [[NSDate st_localCurrentDate] timeIntervalSince1970] * 1000;
    return @(num).debugDescription;
}
+ (NSString*)sha1WithAppSecret:(NSString*)appSecret  nonce:(NSString*)nonce time:(NSString*)time{
    
    NSString * input = [NSString stringWithFormat:@"%@%@%@",appSecret,nonce,time];
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}
@end
